<?php
/**
 * Created by PhpStorm.
 * User: gongm
 * Date: 20818-2-9
 */

namespace app\Http\Controllers\News;

use Illuminate\Http\Request;
use App\Http\Controllers\Api\Controller;

class ArticleController extends Controller
{

    /**
     * 门户首页推荐文章列表
     * @param Request $request
     * @return { resp_msg : { msg_code : 200, msg_desc : 'success' }, resp_data : {} }
     *
     * @SWG\Get(path="/portal/articles/recommends",
     *   tags={"资讯-文章"},
     *   summary="首页推荐接口",
     *   description="用户无需登录，建议传递已登录用户的 access-token；获取分类文章需传递catid",
     *   operationId="getRecommendArticle",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="refresh_time",type="integer",description="刷新时间（首次请求系统自动生成，分页加载更多需传递该值）",required=false),
     *   @SWG\Parameter(in="query",name="size",type="integer",description="分页数量，系统默认20条",required=false),
     *   @SWG\Parameter(in="query",name="page",type="integer",description="第几页，默认“1”",required=false),
     *   @SWG\Parameter(in="query",name="catid",type="integer",description="文章分类ID",required=false),
     *   @SWG\Response(response="200", description="msg_code:200,msg_desc:success"),
     * )
     */
    public function getRecommendArticle(Request $request)
    {
        //return Response::ajaxResponse($this->_getArticle($articleService, $request));

        $data = '';

        return $this->response->setResponseData($data)->getResponse();
    }

    /**
     * 文章列表
     * @param $articleService
     * @param $request
     * @param bool $isTxh
     * @return mixed
     */
    protected function _getArticle($request, $isTxh = false)
    {
        $refreshTime = $request->input('refresh_time', time());
        $limit = $request->input('size', config('news.news_portal_article_default_limit'));
        $page = $request->input('page', 1);
        $catid = $request->input('catid', 0);
        $start = $page > 0 ? ($page - 1) * $limit : 0;
        $result = $articleService->getPortalArticleList($catid, $start, $refreshTime, $limit, $isTxh);
        if ($isTxh) {
            $topTxh = $page == 1 ? $this->_getTopTxh($articleService) : [];

            return Response::responseData(Msg::SUCCESS_GET, ['list' => $result, 'top_txh' => $topTxh]);
        } else {
            if ($page == 1 && ($catid == 0 || $catid > 100)) {
                return Response::responseData(Msg::SUCCESS_GET,
                    ['list' => $result, 'banner' => $this->_getTopBanner($articleService)]);
            } else {
                return Response::responseData(Msg::SUCCESS_GET, ['list' => $result]);
            }
        }
    }

    /**
     * 推荐通心号
     * @param $articleService
     * @return mixed
     */
    protected function _getTopTxh($articleService)
    {
        return $articleService->getTopTxh();
    }

    /**
     * 首页轮播图
     * @param $articleService
     * @return mixed
     */
    protected function _getTopBanner($articleService)
    {
        return $articleService->getNewsArticleTopBanner();
    }

    /**
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     */
    public function getTxhArticle(ArticleService $articleService, Request $request)
    {
        return Response::ajaxResponse($this->_getArticle($articleService, $request, true));
    }

    /**
     * 文章详情
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     * @SWG\Get(path="/news/article/info",
     *   tags={"资讯-文章"},
     *   summary="内容详情接口",
     *   description="用户无需登录，建议传递已登录用户的access-token",
     *   operationId="getArticleInfo",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="aid",type="integer",description="文章id",required=true),
     *   @SWG\Parameter(in="query",name="size",type="integer",description="获取文章评论数，默认获取5条主评论（可能超过5条）",required=false),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function getArticleInfo(ArticleService $articleService, Request $request)
    {
        $aid = intval($request->input('aid', 0));
        if ($aid) {
            $info = $articleService->findArticleInfo($aid, $this->tw_uid);
            if ($info) {
                $limit = $request->input('size', config('news.news_portal_article_comment_limit'));
                $refreshTime = time();
                $info['tags'] = $articleService->findArticleTags($aid);
                $info['comment'] = $articleService->getArticleComment($aid, 0, $limit, $refreshTime);
                $info['total_comment'] = $articleService->countArticleComment($aid);
                $info['is_click_like'] = 0;
                $info['click_like_num'] = $info['click1'];
                unset($info['click1']);
                if ($this->uid > 0) {
                    $click_like = $articleService->findUserArticleClickLike($this->uid, $aid);
                    $info['is_click_like'] = $click_like ? 1 : 0;
                    $info['is_favorite'] = $articleService->findUserIsFavorite($this->uid, $aid) ? 1 : 0;
                } else {
                    $info['is_favorite'] = 0;
                }

                return Response::ajaxResponse(Response::responseData(Msg::SUCCESS_GET, $info));
            }

            return Response::ajaxResponse(Response::responseData(Msg::SUCCESS_GET));
        }
    }

    /**
     * 文章评论
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     * @SWG\Get(path="/news/article/comment",
     *   tags={"资讯-文章"},
     *   summary="文章评论列表接口",
     *   description="用户无需登录",
     *   operationId="getArticleComment",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="aid",type="integer",description="文章id",required=true),
     *   @SWG\Parameter(in="query",name="refresh_time",type="integer",description="刷新时间（首次请求系统自动生成，分页加载更多需传递该值）",required=false),
     *   @SWG\Parameter(in="query",name="size",type="integer",description="获取文章评论条数,默认10条",required=false),
     *   @SWG\Parameter(in="query",name="page",type="integer",description="第几页，默认“1”，如果是内容页查看更多，应为2",required=false),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function getArticleComment(ArticleService $articleService, Request $request)
    {
        $aid = intval($request->input('aid', 0));
        if ($aid) {
            $refreshTime = $request->input('refresh_time', time());
            $limit = $request->input('size', config('news.news_portal_article_comment_list_limit'));
            $page = $request->input('page', 1);
            $start = $page > 0 ? ($page - 1) * $limit : 0;

            return Response::ajaxResponse(Response::responseData(Msg::SUCCESS_GET,
                $articleService->getArticleComment($aid, $start, $limit, $refreshTime)));
        }
    }

    /**
     * 添加文章评论
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     * @SWG\Post(path="/news/article/comment",
     *   tags={"资讯-文章"},
     *   summary="添加文章评论接口",
     *   description="用户需登录",
     *   operationId="addArticleComment",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="aid",type="integer",description="文章id",required=true),
     *   @SWG\Parameter(in="query",name="pid",type="integer",description="回复的评论id",required=false),
     *   @SWG\Parameter(in="query",name="comment",type="string",description="评论内容",required=true),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function addArticleComment(ArticleService $articleService, Request $request)
    {
        /*if($this->uid){
        }else{
            return Response::ajaxResponse(Response::responseData(Msg::ERROR_ACCESS_TOKEN_EXPIRE));
        }*/
        $aid = intval($request->input('aid', 0));
        $pid = intval($request->input('pid', 0));
        if ($aid > 0) {
            $comment = trim(strip_tags($request->input('comment', '')));
            if ($comment) {
                $result = $articleService->addArticleComment($this->uid, $aid, $comment, $pid);

                return Response::ajaxResponse(Response::responseData(Msg::SUCCESS_GET, $result));
            } else {
                return Response::ajaxResponse(Response::responseData(Msg::ERROR_NEWS_ARTICLE_COMMENT_INVALID, []));
            }
        }

        return Response::ajaxResponse(Response::responseData(Msg::ERROR_NEWS_ARTICLE_ADD_COMMENT));
    }

    /**
     * 删除用户自己的评论
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     * @SWG\Delete(path="/news/article/comment",
     *   tags={"资讯-文章"},
     *   summary="删除用户评论接口",
     *   description="用户需登录",
     *   operationId="deleteArticleComment",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="cid",type="integer",description="评论id",required=true),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function deleteArticleComment(ArticleService $articleService, Request $request)
    {
        $cid = intval($request->input('cid', 0));
        if ($cid) {
            $res = $articleService->deleteUserArticleComment($this->uid, $cid);

            return Response::ajaxResponse($res);
        }

        return Response::ajaxResponse(Response::responseData(Msg::ERROR_NEWS_ARTICLE_DELETE_COMMENT));
    }

    /**
     * 取消收藏/收藏文章
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     * @SWG\Put(path="/news/article/collection",
     *   tags={"资讯-文章"},
     *   summary="文章取消收藏/收藏接口",
     *   description="用户需登录",
     *   operationId="updateUserArticleFavorite",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="aid",type="integer",description="文章id",required=true),
     *   @SWG\Parameter(in="query",name="del",type="integer",description="默认0，收藏文章",required=false),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function updateUserArticleFavorite(ArticleService $articleService, Request $request)
    {
        $aid = intval($request->input('aid', 0));
        if ($aid > 0) {
            $del = intval($request->input('del', 0));
            if ($del) {
                $result = $articleService->deleteUserArticleFavorite($this->uid, $aid);
            } else {
                $result = $articleService->addUserArticleFavorite($this->uid, $aid);
            }

            return Response::ajaxResponse($result);
        }

        return Response::ajaxResponse(Response::responseData(Msg::ERROR_NEWS_ARTICLE_UPDATE_FAVORITE));
    }

    /**
     * 添加文章点赞
     * @param ArticleService $articleService
     * @param Request $request
     * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory
     *
     * @SWG\Post(path="/news/article/clicklike",
     *   tags={"资讯-文章"},
     *   summary="文章点赞接口",
     *   description="用户需登录",
     *   operationId="addUserArticleClickLike",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="aid",type="integer",description="文章id",required=true),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function addUserArticleClickLike(ArticleService $articleService, Request $request)
    {
        $aid = intval($request->input('aid', 0));
        if ($aid > 0) {
            $result = $articleService->addUserArticleClickLike($this->uid, $aid);

            return Response::ajaxResponse($result);
        } else {
            return Response::ajaxResponse(Response::responseData(Msg::ERROR_NEWS_ARTICLE_CLICK_LIKE));
        }
    }

    /**
     * 分享时传入url地址，根据地址判断返回title和封面图
     * 
     *
     * @SWG\Get(path="/news/share/info",
     *   tags={"资讯-文章"},
     *   summary="处理分享的url",
     *   description="根据分享的url地址判返回title和封面图",
     *   operationId="getShareUrlInfo",
     *   produces={"application/json"},
     *   @SWG\Parameter(in="query",name="shareurl",type="string",description="分享的url地址",required=true),
     *   @SWG\Response(response="200", description="code:20002,msg:获取数据成功"),
     * )
     */
    public function getShareUrlInfo(ArticleService $articleService, Request $request)
    {
        $shareUrl = urldecode($request->input('shareurl'));
        $result = $articleService->makeShareUrl($shareUrl);
        return Response::ajaxResponse($result);
    }
}